import axios from 'axios';
import { Message } from 'element-ui';

const param = (obj) => {
	var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
	for(name in obj) {
		value = obj[name];
		if(value instanceof Array) {
			for(i=0; i < value.length; ++i) {
				subValue = value[i];
				fullSubName = name + '[' + i + ']';
				innerObj = {};
				innerObj[fullSubName] = subValue;
				query += param(innerObj) + '&';
			}
		} else if(value instanceof Object) {
			for(subName in value) {
				subValue = value[subName];
				fullSubName = name + '.' + subName; //+ '[' + subName + ']';
				innerObj = {};
				innerObj[fullSubName] = subValue == null ? '' : subValue;

				query += param(innerObj) + '&';
			}
		} else if(value !== undefined && value !== null && value !== "")
			query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
	}
	return query.length ? query.substr(0, query.length - 1) : query;
};
const baseUrl = '/'
const newInstance = axios.create({
	baseURL: baseUrl,
	transformRequest: [ data =>  param(data) ],
	timeout: 600000,
	responseType: 'json'
});
newInstance.interceptors.request.use( req => {
	if (req.params) {
		Object.keys(req.params).forEach( key => {
			let curVal = req.params[key];
			if (curVal === "" || curVal === undefined || curVal === null) {
				delete req.params[key];
			}
		});
	}
	return req;
});
newInstance.interceptors.response.use( res => {
	let data = res.data;
	if (data && (data.code !== '200' || data.resultCode)) {
		let message = data.message || data.resultDesc;
		Message.error(message || '未知错误');
		return Promise.reject(data);
	} else {
		return data;
	}
}, error => {
	if (error.response) {
		Message.error(`接口错误，返回状态：${error.response.status}`);
    }
    return Promise.reject(error.response.data);
});
// 指定post头
newInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

export default newInstance;
